#include "mainwindow.h"
#include "pyconnector.h"

#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    resize(800, 500);
    m_spliter = new QSplitter(Qt::Horizontal, this);
    m_painter = new PainterWidget(m_spliter);
    m_list = new QListWidget(m_spliter);
    m_spliter->addWidget(m_painter);
    m_spliter->addWidget(m_list);
    m_spliter->setStretchFactor(0, 8);
    m_spliter->setStretchFactor(1, 3);
    this->setCentralWidget(m_spliter);
    // Property Setting
    m_list->setAlternatingRowColors(true);
}

MainWindow::~MainWindow() {}

void MainWindow::addItem(const QString &str)
{
    ItemWidget *itemWidget = new ItemWidget(this);
    itemWidget->setData(str);
    QListWidgetItem *item = new QListWidgetItem();
    item->setSizeHint(QSize(50, 30));
    m_list->addItem(item);
    m_list->setItemWidget(item, itemWidget);
}

QString MainWindow::execRecognition(const QString &path)
{
    if (path == "") {
        qDebug() << "[ERROR] Input Image Path is Null";
        return "";
    }
    PyObject * pFunc = PyConnector::GetInstance()->PyLoadModFunction("Py_proc", "process");
    if (!pFunc) {
        qDebug() << "[ERROR] Get Mod Function is Null";
        return "";
    }
    PyObject *pPara = PyTuple_New(1);
    PyTuple_SET_ITEM(pPara, 0, Py_BuildValue("s", path.toStdString().c_str()));
    PyObject *pRet = PyConnector::GetInstance()->PyCallFunction(pFunc, pPara);
    PyObject *repr = PyObject_Repr(pRet);
    PyObject *imgfrompy = PyUnicode_AsEncodedString(repr, "utf-8", "strict");
    char *res = PyBytes_AsString(imgfrompy);
    return res;
}

/******************* ItemWidget *******************/

ItemWidget::ItemWidget(QWidget *parent) : QWidget(parent)
{
    m_label = new QLabel(this);
    m_label->setFont(QFont(nullptr, 20, 3));
    m_label->setAlignment(Qt::AlignCenter);
}

ItemWidget::~ItemWidget()
{}

void ItemWidget::setData(const QString &str)
{
    m_label->setText(str);
}
